<template>
  <view class="container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @tap="goBack">
        <text class="iconfont icon-back"></text>
      </view>
      <text class="title">请假申请</text>
    </view>

    <!-- 请假表单 -->
    <view class="leave-form">
      <!-- 请假类型 -->
      <view class="form-item">
        <text class="form-label">请假类型</text>
        <view class="form-input-wrapper">
          <picker 
            :value="leaveTypeIndex" 
            :range="leaveTypes" 
            range-key="label" 
            @change="onLeaveTypeChange"
          >
            <view class="picker-view">
              <text>{{ leaveTypes[leaveTypeIndex].label }}</text>
              <text class="iconfont icon-arrow-down"></text>
            </view>
          </picker>
        </view>
      </view>

      <!-- 请假时间 -->
      <view class="form-item">
        <text class="form-label">开始时间</text>
        <view class="form-input-wrapper">
          <picker 
            mode="date" 
            :value="startDate" 
            start="2023-01-01" 
            end="2023-12-31" 
            @change="onStartDateChange"
          >
            <view class="picker-view">
              <text>{{ startDate }}</text>
              <text class="iconfont icon-calendar"></text>
            </view>
          </picker>
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">开始时段</text>
        <view class="form-input-wrapper">
          <picker 
            :value="startTimeIndex" 
            :range="timePeriods" 
            @change="onStartTimeChange"
          >
            <view class="picker-view">
              <text>{{ timePeriods[startTimeIndex] }}</text>
              <text class="iconfont icon-clock"></text>
            </view>
          </picker>
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">结束时间</text>
        <view class="form-input-wrapper">
          <picker 
            mode="date" 
            :value="endDate" 
            start="2023-01-01" 
            end="2023-12-31" 
            @change="onEndDateChange"
          >
            <view class="picker-view">
              <text>{{ endDate }}</text>
              <text class="iconfont icon-calendar"></text>
            </view>
          </picker>
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">结束时段</text>
        <view class="form-input-wrapper">
          <picker 
            :value="endTimeIndex" 
            :range="timePeriods" 
            @change="onEndTimeChange"
          >
            <view class="picker-view">
              <text>{{ timePeriods[endTimeIndex] }}</text>
              <text class="iconfont icon-clock"></text>
            </view>
          </picker>
        </view>
      </view>

      <!-- 请假天数 -->
      <view class="form-item">
        <text class="form-label">请假天数</text>
        <view class="form-input-wrapper">
          <text class="leave-days">{{ leaveDays }}天</text>
        </view>
      </view>

      <!-- 请假原因 -->
      <view class="form-item">
        <text class="form-label">请假原因</text>
        <view class="form-input-wrapper textarea-wrapper">
          <textarea 
            v-model="leaveReason" 
            placeholder="请输入请假原因（必填）" 
            maxlength="200" 
            class="leave-reason"
          ></textarea>
          <text class="word-count">{{ leaveReason.length }}/200</text>
        </view>
      </view>

      <!-- 附件上传 -->
      <view class="form-item">
        <text class="form-label">证明材料</text>
        <view class="attachment-area">
          <view 
            class="attachment-item" 
            v-for="(item, index) in attachments" 
            :key="index"
          >
            <image :src="item.path" mode="aspectFill" class="attachment-preview"></image>
            <view class="attachment-delete" @tap="removeAttachment(index)">
              <text class="iconfont icon-delete"></text>
            </view>
          </view>
          
          <view class="attachment-add" v-if="attachments.length < 3" @tap="addAttachment">
            <text class="iconfont icon-add"></text>
            <text>上传图片</text>
          </view>
        </view>
        <text class="attachment-tip">选填，最多可上传3张图片</text>
      </view>

      <!-- 审批人 -->
      <view class="form-item">
        <text class="form-label">审批人</text>
        <view class="form-input-wrapper">
          <picker 
            :value="approverIndex" 
            :range="approvers" 
            range-key="name" 
            @change="onApproverChange"
          >
            <view class="picker-view">
              <text>{{ approvers[approverIndex].name }}</text>
              <text class="iconfont icon-arrow-down"></text>
            </view>
          </picker>
        </view>
      </view>

      <!-- 抄送人 -->
      <view class="form-item">
        <text class="form-label">抄送人</text>
        <view class="form-input-wrapper">
          <picker 
            mode="selector" 
            :value="ccPersonIndex" 
            :range="ccPersons" 
            range-key="name" 
            @change="onCcPersonChange"
          >
            <view class="picker-view">
              <text>{{ ccPersons[ccPersonIndex].name }}</text>
              <text class="iconfont icon-arrow-down"></text>
            </view>
          </picker>
        </view>
      </view>
    </view>

    <!-- 确认按钮 -->
    <view class="button-area">
      <button class="submit-btn" @tap="submitLeaveApplication">提交申请</button>
    </view>

    <!-- 提示弹窗 -->
    <view class="modal-mask" v-if="showModal" @tap="hideModal"></view>
    <view class="modal-container" v-if="showModal">
      <view class="modal-content">
        <view class="modal-icon">
          <text class="iconfont icon-success"></text>
        </view>
        <view class="modal-title">申请已提交</view>
        <view class="modal-desc">您的请假申请已提交，请等待审批</view>
      </view>
      <view class="modal-footer">
        <button class="modal-btn" @tap="goToApplicationList">查看申请记录</button>
        <button class="modal-btn primary" @tap="goBack">返回考勤管理</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    const today = this.formatDate(new Date())
    
    return {
      // 请假类型选择
      leaveTypeIndex: 0,
      leaveTypes: [
        { label: '事假', value: 'personal' },
        { label: '病假', value: 'sick' },
        { label: '年假', value: 'annual' },
        { label: '婚假', value: 'marriage' },
        { label: '产假', value: 'maternity' },
        { label: '丧假', value: 'funeral' },
        { label: '其他', value: 'other' }
      ],
      
      // 时间选择
      startDate: today,
      endDate: today,
      startTimeIndex: 0,
      endTimeIndex: 1,
      timePeriods: ['上午', '下午', '全天'],
      
      // 请假天数（自动计算）
      leaveDays: 0.5,
      
      // 请假原因
      leaveReason: '',
      
      // 附件
      attachments: [],
      
      // 审批人
      approverIndex: 0,
      approvers: [
        { name: '王主任（教务处）', id: 1 },
        { name: '李主任（人事处）', id: 2 },
        { name: '张校长', id: 3 }
      ],
      
      // 抄送人
      ccPersonIndex: 0,
      ccPersons: [
        { name: '不抄送', id: 0 },
        { name: '赵老师', id: 4 },
        { name: '钱老师', id: 5 },
        { name: '孙老师', id: 6 }
      ],
      
      // 提示弹窗
      showModal: false
    }
  },
  mounted() {
    // 初始计算请假天数
    this.calculateLeaveDays()
  },
  methods: {
    // 导航返回
    goBack() {
      uni.navigateBack()
    },
    
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    // 请假类型变更
    onLeaveTypeChange(e) {
      this.leaveTypeIndex = e.detail.value
    },
    
    // 开始日期变更
    onStartDateChange(e) {
      this.startDate = e.detail.value
      
      // 如果开始日期大于结束日期，则同步更新结束日期
      if (new Date(this.startDate) > new Date(this.endDate)) {
        this.endDate = this.startDate
      }
      
      this.calculateLeaveDays()
    },
    
    // 结束日期变更
    onEndDateChange(e) {
      this.endDate = e.detail.value
      
      // 如果结束日期小于开始日期，则同步更新开始日期
      if (new Date(this.endDate) < new Date(this.startDate)) {
        this.startDate = this.endDate
      }
      
      this.calculateLeaveDays()
    },
    
    // 开始时段变更
    onStartTimeChange(e) {
      this.startTimeIndex = e.detail.value
      
      // 如果开始和结束是同一天，确保时间段合理
      if (this.startDate === this.endDate && this.startTimeIndex > this.endTimeIndex) {
        this.endTimeIndex = this.startTimeIndex
      }
      
      this.calculateLeaveDays()
    },
    
    // 结束时段变更
    onEndTimeChange(e) {
      this.endTimeIndex = e.detail.value
      
      // 如果开始和结束是同一天，确保时间段合理
      if (this.startDate === this.endDate && this.endTimeIndex < this.startTimeIndex) {
        this.startTimeIndex = this.endTimeIndex
      }
      
      this.calculateLeaveDays()
    },
    
    // 计算请假天数
    calculateLeaveDays() {
      const startDate = new Date(this.startDate)
      const endDate = new Date(this.endDate)
      
      // 计算相差的天数
      const diffTime = Math.abs(endDate - startDate)
      const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
      
      let totalDays = diffDays
      
      // 如果是同一天
      if (diffDays === 0) {
        // 如果都选择全天或相同的半天，则为0.5天
        if (this.startTimeIndex === this.endTimeIndex && this.startTimeIndex !== 2) {
          totalDays = 0.5
        } 
        // 如果一个是上午一个是下午，或者任一是全天，则为1天
        else {
          totalDays = 1
        }
      } 
      // 不是同一天
      else {
        // 加上开始日的天数（半天或全天）
        if (this.startTimeIndex === 2) {
          totalDays += 1
        } else {
          totalDays += 0.5
        }
        
        // 加上结束日的天数（半天或全天）
        if (this.endTimeIndex === 2) {
          totalDays += 1
        } else {
          totalDays += 0.5
        }
      }
      
      this.leaveDays = totalDays
    },
    
    // 审批人变更
    onApproverChange(e) {
      this.approverIndex = e.detail.value
    },
    
    // 抄送人变更
    onCcPersonChange(e) {
      this.ccPersonIndex = e.detail.value
    },
    
    // 添加附件
    addAttachment() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: res => {
          // 处理选择的图片
          if (this.attachments.length < 3) {
            const newAttachment = {
              path: res.tempFilePaths[0],
              name: res.tempFilePaths[0].split('/').pop(),
              size: '未知'
            }
            
            this.attachments.push(newAttachment)
          }
        }
      })
    },
    
    // 移除附件
    removeAttachment(index) {
      this.attachments.splice(index, 1)
    },
    
    // 提交请假申请
    submitLeaveApplication() {
      // 表单验证
      if (this.leaveReason.trim() === '') {
        uni.showToast({
          title: '请输入请假原因',
          icon: 'none'
        })
        return
      }
      
      // 显示提交中
      uni.showLoading({
        title: '提交中...'
      })
      
      // 构建请假申请数据
      const leaveData = {
        leaveType: this.leaveTypes[this.leaveTypeIndex].value,
        startDate: this.startDate,
        startTimePeriod: this.timePeriods[this.startTimeIndex],
        endDate: this.endDate,
        endTimePeriod: this.timePeriods[this.endTimeIndex],
        leaveDays: this.leaveDays,
        reason: this.leaveReason,
        attachments: this.attachments.map(a => a.path),
        approverId: this.approvers[this.approverIndex].id,
        ccPersonId: this.ccPersons[this.ccPersonIndex].id
      }
      
      console.log('请假申请数据:', leaveData)
      
      // 模拟网络请求
      setTimeout(() => {
        uni.hideLoading()
        
        // 显示成功弹窗
        this.showModal = true
      }, 1500)
    },
    
    // 隐藏弹窗
    hideModal() {
      this.showModal = false
    },
    
    // 前往申请记录页面
    goToApplicationList() {
      this.hideModal()
      uni.navigateTo({
        url: '/pages/management/leave-record'
      })
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #f6f7fb;
  padding-bottom: 100rpx;
}

.header {
  display: flex;
  align-items: center;
  height: 90rpx;
  background-color: #4080ff;
  padding: 0 30rpx;
  color: #fff;
  
  .back-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .iconfont {
      font-size: 40rpx;
    }
  }
  
  .title {
    flex: 1;
    text-align: center;
    font-size: 36rpx;
    font-weight: bold;
    padding-right: 60rpx;
  }
}

.leave-form {
  background: #fff;
  padding: 0 30rpx;
  
  .form-item {
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    .form-label {
      font-size: 28rpx;
      color: #333;
      font-weight: bold;
      margin-bottom: 20rpx;
      display: block;
    }
    
    .form-input-wrapper {
      position: relative;
      
      .picker-view {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 80rpx;
        padding: 0 20rpx;
        background: #f8f8f8;
        border-radius: 8rpx;
        
        text {
          font-size: 28rpx;
          color: #333;
        }
        
        .iconfont {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .leave-days {
        display: flex;
        align-items: center;
        height: 80rpx;
        padding: 0 20rpx;
        background: #f8f8f8;
        border-radius: 8rpx;
        font-size: 28rpx;
        color: #333;
      }
      
      &.textarea-wrapper {
        padding: 20rpx;
        background: #f8f8f8;
        border-radius: 8rpx;
        position: relative;
        
        .leave-reason {
          width: 100%;
          height: 200rpx;
          font-size: 28rpx;
          line-height: 1.5;
        }
        
        .word-count {
          position: absolute;
          right: 20rpx;
          bottom: 20rpx;
          font-size: 24rpx;
          color: #999;
        }
      }
    }
    
    .attachment-area {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 10rpx;
      
      .attachment-item, .attachment-add {
        width: 160rpx;
        height: 160rpx;
        margin-right: 20rpx;
        margin-bottom: 20rpx;
        border-radius: 8rpx;
        overflow: hidden;
      }
      
      .attachment-item {
        position: relative;
        
        .attachment-preview {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        
        .attachment-delete {
          position: absolute;
          top: 0;
          right: 0;
          width: 40rpx;
          height: 40rpx;
          background: rgba(0, 0, 0, 0.6);
          display: flex;
          align-items: center;
          justify-content: center;
          
          .iconfont {
            font-size: 24rpx;
            color: #fff;
          }
        }
      }
      
      .attachment-add {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background: #f8f8f8;
        
        .iconfont {
          font-size: 40rpx;
          color: #999;
          margin-bottom: 10rpx;
        }
        
        text {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
    
    .attachment-tip {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.button-area {
  padding: 40rpx 30rpx;
  
  .submit-btn {
    height: 90rpx;
    line-height: 90rpx;
    background: #4080ff;
    color: #fff;
    font-size: 32rpx;
    border-radius: 45rpx;
  }
}

// 弹窗样式
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  z-index: 100;
}

.modal-container {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 560rpx;
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  z-index: 101;
  
  .modal-content {
    padding: 50rpx 30rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .modal-icon {
      width: 120rpx;
      height: 120rpx;
      background: rgba(76, 175, 80, 0.1);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 30rpx;
      
      .iconfont {
        font-size: 60rpx;
        color: #4caf50;
      }
    }
    
    .modal-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .modal-desc {
      font-size: 28rpx;
      color: #666;
      text-align: center;
    }
  }
  
  .modal-footer {
    display: flex;
    border-top: 1rpx solid #f0f0f0;
    
    .modal-btn {
      flex: 1;
      height: 100rpx;
      line-height: 100rpx;
      text-align: center;
      font-size: 32rpx;
      color: #666;
      background: #fff;
      border-radius: 0;
      margin: 0;
      
      &.primary {
        color: #4080ff;
        font-weight: bold;
      }
      
      &:not(:last-child) {
        border-right: 1rpx solid #f0f0f0;
      }
    }
  }
}
</style> 